<template>
	<div>

		<div class="app-container">
			<TopInfo />

			<div class="mt-6 text-right">
				<el-button @click="cancel">{{ $t('public.cancel') }}</el-button>
				<el-button type="primary" @click="add">{{ $t('presets.info.addLayout') }}</el-button>
			</div>
		</div>

		<div class="app-container" v-loading="layoutRequest.loading.value">
			<!-- 所有模板、组件、比正常尺寸缩小三倍 -->

			<div class="w-full flex flex-wrap">

				<div class="relative box-content"
					:style="'width:' + wrapSize.width + 'px;height:' + wrapSize.height + 'px;border:1px solid #ccc;'">

					<el-tooltip v-for="item in layoutRequest.data.value" :key="item.id" :content="item.name"
						placement="top-start">
						<div class="absolute border border-dashed border-main cursor-pointer overflow-hidden flex justify-center items-center"
							:style="{
								width: item.width / ratio + 'px',
								height: item.height / ratio + 'px',
								left: item.left / ratio + 'px',
								top: item.top / ratio + 'px'
							}" @click="edit(item)">
							{{ item.name }}
						</div>
					</el-tooltip>

				</div>
			</div>

		</div>


		<el-dialog v-model="formShow" center width="30%" :title="$t('presets.info.layoutInfo')"
			@close="formShow = false">
			<el-form v-if="formShow" :model="formData" :rules="formRules" :label-width="language=='en'?'130':'100px'" ref="ruleFormRef">

				<el-form-item :label="$t('presets.info.areaName') + ':'" prop="name">
					<el-input v-model="formData.name" :placeholder="$t('message.pleaseEnter')" />
				</el-form-item>

				<el-form-item :label="$t('presets.info.layoutHeight') + ':'" prop="height">
					<el-input v-model="formData.height" :placeholder="$t('message.pleaseEnter')" type="number">
						<template #append>
							px
						</template>
					</el-input>
				</el-form-item>

				<el-form-item :label="$t('presets.info.layoutWidth') + ':'" prop="width">
					<el-input v-model="formData.width" :placeholder="$t('message.pleaseEnter')" type="number">
						<template #append>
							px
						</template>
					</el-input>
				</el-form-item>

				<el-form-item :label="$t('presets.info.leftDeviation') + ':'" prop="left">
					<el-input v-model="formData.left" :placeholder="$t('message.pleaseEnter')" type="number">
						<template #append>
							px
						</template>
					</el-input>
				</el-form-item>

				<el-form-item :label="$t('presets.info.topDeviation') + ':'" prop="top">
					<el-input v-model="formData.top" :placeholder="$t('message.pleaseEnter')" type="number">
						<template #append>
							px
						</template>
					</el-input>
				</el-form-item>

				<el-form-item :label="$t('presets.info.specifiedRange') + ':'" prop="plugin_id">
					<el-select v-model="formData.plugin_id" :placeholder="$t('message.pleaseSelect')" clearable multiple
						filterable>
						<el-option v-for="item in pluginList" :key="item.value" :label="item.value + ' - ' + item.label"
							:value="item.value" />
					</el-select>
				</el-form-item>

				<div class="w-full flex justify-between">
					<div>
						<el-button @click="del">{{ $t('public.del') }}</el-button>
					</div>
					<div class="inline-block">
						<el-button type="primary" @click="submit(ruleFormRef)">{{ $t('public.save') }}</el-button>
						<el-button @click="formShow = false">{{ $t('public.cancel') }}</el-button>
					</div>
				</div>

			</el-form>
		</el-dialog>

	</div>
</template>

<script lang="ts" setup>
import { useI18n } from 'vue-i18n' 
const { t: $t } = useI18n()
import TopInfo from '@/components/TopInfo/index.vue';
import { getLayoutList, addlayout, updatelayout, dellayout, getpluginsList } from '@/api/presets';
import { useRoute, useRouter } from "vue-router";
import useRequest from "@/hooks/useRequset";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import { onMounted } from "vue";
import { Preset } from "@/types";
let language = ref()
const { locale } = useI18n()
onMounted(() => {
	language.value = locale.value
})
let ruleFormRef = ref<any>();
let router = useRouter()
const route = useRoute()
let layoutId = 0;

const ratio = 2;
const wrapSize = reactive({
	width: 0,
	height: 0
})
let cancel = () => {
	router.back()
}
onMounted(() => {
	const params = JSON.parse(decodeURI(route.query.l as string)).info as {
		id: number,
		resolution: string
	}
	console.log('params', params)
	layoutId = params.id
	const size = params.resolution.split('*').map(item => Number(item))
	wrapSize.width = size[0] / ratio
	wrapSize.height = size[1] / ratio
	layoutRequest.getData({})
})

const layoutRequest = useRequest(() => {
	return getLayoutList({ template_id: layoutId })
}
)


// 获取组件列表
const pluginRequest = useRequest(
	() => {
		return getpluginsList({})
	}
)
pluginRequest.getData({})
const pluginList = computed(() => {
	return pluginRequest.data.value.map(item => ({
		label: item.plugin_name,
		value: item.id
	}))
})

// 表单数据
const formShow = ref(false);
const formData = reactive({
	id: 0,
	name: '',
	height: '',
	width: '',
	left: '',
	top: '',
	plugin_id: [] as number[]
})
const formRules = {
	name: { required: true, message:  $t('message.pleaseEnter'), trigger: 'blur' },
	height: { required: true, message:  $t('message.pleaseEnter'), trigger: 'blur' },
	width: { required: true, message:  $t('message.pleaseEnter'), trigger: 'blur' },
	left: { required: true, message:  $t('message.pleaseEnter'), trigger: 'blur' },
	top: { required: true, message:  $t('message.pleaseEnter'), trigger: 'blur' },
	plugin_id: { required: true, message:  $t('message.pleaseSelect'), trigger: 'change' },
}

// 添加布局
let add = () => {
	formData.id = 0
	formData.name = ''
	formData.height = ''
	formData.width = ''
	formData.left = ''
	formData.top = ''
	formData.plugin_id = []
	formShow.value = true
}

// 修改布局
const edit = (item: Preset.Layout) => {
	formData.id = item.id
	formData.name = item.name
	formData.width = item.width.toString()
	formData.height = item.height.toString()
	formData.left = item.left.toString()
	formData.top = item.top.toString()
	if (item.plugin_id) {
		formData.plugin_id = item.plugin_id.split(',').map(item => Number(item))
	} else {
		formData.plugin_id = []
	}

	formShow.value = true
}

// 删除布局
let del = () => {
	ElMessageBox.confirm($t('message.delData'))
		.then(res => {
			dellayout({ id: formData.id }).then(res => {
				if (res.state == 200) {
					ElMessage({
						message: $t('message.delSuccess'),
						type: 'success'
					})
					formShow.value = false
					layoutRequest.getData({})
					return
				}
				ElMessage({
					message: $t('message.networkFailed'),
					type: 'error'
				})
			})
		}).catch(err => {
			console.log('取消')
		})
}

// 数据提交
let submit = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate(async (valid, fields) => {
		if (valid) {
			let numheight = Number(formData.height) + Number(formData.top)
			let numWidth = Number(formData.width) + Number(formData.left)
			if (numheight > wrapSize.height * ratio) {
				ElMessage({
					message: $t('message.notHeight'),
					type: 'error'
				})
				return
			}

			if (numWidth > wrapSize.width * ratio) {
				ElMessage({
					message:  $t('message.notWidth'),
					type: 'error'
				})
				return
			}
			const data = {
				name: formData.name,
				template_id: layoutId,
				height: formData.height,
				width: formData.width,
				left: formData.left,
				top: formData.top,
				plugin_id: formData.plugin_id.join(',')
			}

			let res;
			if (formData.id === 0) {
				res = await addlayout(data)
			} else {
				res = await updatelayout({ id: formData.id, ...data })
			}
			if (res.state == 200) {
				ElMessage({
					message: $t('message.modifySuccess'),
					type: 'success'
				})
				formShow.value = false
				layoutRequest.getData({})
				return
			}
			ElMessage({
				message: $t('message.networkFailed'),
				type: 'error'
			})
		}
	})
}


</script>
